#include "GrayscaleReconstructAction.h"
#include <QImage>
#include <cmath>
#include "GrayscaleReconstruct.h"
#include "Layer.h"
#include "Work.h"
#include "FilterLinear.h"



GrayscaleReconstructAction::GrayscaleReconstructAction ()
: AbstractAction (), _structElem (Core< int > (QSize (10, 10))), _type (1)
{

}

void GrayscaleReconstructAction::updatePreview (QRect viewport)
{
	Ptr< Layer > pCurLayer = __pTargetWork->getDoc ()->getCurrentLayer ();

	bool isPreview = true;
	if (viewport.isEmpty ()) {
		isPreview = false;
		viewport = pCurLayer->getRegion ();
	}

	QRect updateRegion = viewport & pCurLayer->getRegion ();

	QPoint oSrcImg = pCurLayer->getRegion ().topLeft ();
	QPoint oViewport = viewport.topLeft ();
	QPoint oUpdate = updateRegion.topLeft ();

	QRect processRegion = updateRegion;
	processRegion.translate (-oSrcImg);

	Ptr< QImage > pProcessSrc = new QImage (pCurLayer->getImage ()
			->copy (processRegion));
	GrayscaleReconstruct reconstruct (_structElem);
	if (_type == 0)
		reconstruct.setType (GrayscaleReconstruct::OBR);
	else
		reconstruct.setType (GrayscaleReconstruct::CBR);
	Ptr< QImage > pProcessResult = reconstruct.process (pProcessSrc);

	if (isPreview)
		pCurLayer->setPreviewImage (pProcessResult);
	else
		pCurLayer->setImage (pProcessResult);

}

void GrayscaleReconstructAction::handleStartEvent ()
{
	__pTargetWork->getDoc ()->getCurrentLayer ()->openPreview ();
}

void GrayscaleReconstructAction::rejectAction ()
{
	__pTargetWork->getDoc ()->getCurrentLayer ()->closePreview ();
}

void GrayscaleReconstructAction::applyAction ()
{
	updatePreview (QRect ());
	__pTargetWork->getDoc ()->getCurrentLayer ()->closePreview ();
}

void GrayscaleReconstructAction::setStructElem (Core< int > structElem)
{
	_structElem = structElem;
}

void GrayscaleReconstructAction::setActionType (int t)
{
	_type = t;
}
